/*
 * Copyright 2011 www.pretty-tools.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


#pragma once

#include "UpdateDlg.h"
#include "xml/XmlParser.h"
#include "xml/xml_op.h"

extern CAtlModule* g_pAtlModule;

struct UpdateInfo
{
    CString version;
    CString link;
};

XML_SERIALIZE_MAP(UpdateInfo)
    XML_MAP_ELEMENT(version)
    XML_MAP_ELEMENT(link)
XML_END_SERIALIZE_MAP()

class CheckForUpdateThread : public Runnable
{
public:
    CheckForUpdateThread(void)
    {
        if (g_pAtlModule) g_pAtlModule->Lock();
    }

    ~CheckForUpdateThread(void)
    {
        if (g_pAtlModule) g_pAtlModule->Unlock();
    }

    void CheckForUpdate()
    {
        ATLTRACE("Looking for update\n");

        CString strUpdateURL;
        if (!strUpdateURL.LoadString(IDS_UPDATE_URL))
            return;

        HTTP::Connection connection;
        if (!connection.Open(strUpdateURL))
            return;

        CStringA response;
        if (!connection.GetResponse(response))
            return;

        UpdateInfo info;
        if (!(response >> info))
            return;

        ATLTRACE( _T("Last version: %s\n"), info.version);
        ATLTRACE( _T("Update link:  %s\n"), info.link);

        if (info.version.IsEmpty() || info.link.IsEmpty())
            return;

        if (info.version != UTIL::GetVersion())
        {
            if (CUpdateDlg().DoModal() == IDOK)
            {
                WEBBrowser browser(WEBBrowser::NewInstance());
                if (SUCCEEDED(browser.Navigate(info.link)))
                    browser.Visible = true;
            }
        }
    }

    void Run()
    {
        CoInitialize(NULL);

        CheckForUpdate();

        delete this;

        CoUninitialize();
    }
};
